<script lang="ts" setup>
import { ref, unref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { message } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import { addOrSaveDict } from '#/api';

import { useFormSchema } from './dict.data';

const emits = defineEmits(['onSuccess']);
const currentData = ref({});
const [BaseForm, formApi] = useVbenForm({
  commonConfig: {
    // 所有表单项
    componentProps: {
      class: 'w-full',
    },
  },
  schema: useFormSchema(),
  showDefaultActions: false,
  wrapperClass: 'grid-cols-1',
});
const [Modal, modalApi] = useVbenModal({
  title: '字典添加',
  onOpenChange(isOpen) {
    if (isOpen) {
      initData();
    }
  },
  onConfirm() {
    onSubmit();
  },
});

const initData = async () => {
  const data = modalApi.getData();
  currentData.value = data.records;

  if (data.type === 'edit') {
    const rows = data.records;
    formApi.setValues({ ...rows });
  } else {
    await formApi.resetForm();
  }
};

/** 提交 */
const onSubmit = async () => {
  const data = modalApi.getData();
  const values = await formApi.getValues();
  const params = { ...values };
  modalApi.close();

  if (data.type === 'edit') {
    params.id = unref(currentData)._id;
  }
  await addOrSaveDict(params);
  message.success(data.type === 'edit' ? '修改成功' : '添加成功');
  modalApi.close();
  emits('onSuccess');
};
</script>
<template>
  <Modal class="w-[550px]"> <BaseForm /> </Modal>
</template>
